/*
 * @Author: jiayi
 * @Date:   2017-11-04 12:23:39
 * @Last Modified by:   嘉怡吖，马晓丰, 罗文康
 * @Last Modified time: 2018-07-17
 */
var fpg_guid = null;
var fpg_cookiePrefix = 'fpg';
var fpg_historyId = '#fpg_history';
var fpg_history_click_funName = 'fpg_history_click';
jQuery(document).ready(function ($) {
    checkIsRunState(fpg_cookiePrefix, function (guid) {
        fpg_guid = guid;
        $("#FPG-execute").text('运行中...');
        $('#FPG-execute').attr('disabled', 'disabled');
        $(fpg_historyId).hide();
        fpg_polling();
    });

    initHistoryDropDownMenu(fpg_cookiePrefix, fpg_historyId, fpg_history_click_funName);
    //addItemToHistory(fpg_cookiePrefix, fpg_historyId, 'wu_1cc2tsp8p13cj12re1rj91mha113e1', new Date(), fpg_history_click_funName);

    function setFpgRunState(isRun) {
        if (isRun) {
            $("#FPG-execute").text('运行中...');
            $('#FPG-execute').attr('disabled', 'disabled');
            $(fpg_historyId).hide();
            setRunState(fpg_cookiePrefix, true, fpg_guid);
        } else {
            $('#FPG-execute').removeAttr('disabled');
            $(fpg_historyId).show();
            $("#FPG-execute").text('运行');
            setRunState(fpg_cookiePrefix, false);
        }
    }

    //点击运行 执行算法 成功后获得path
    $("#FPG-execute").click(function (event) {
        //$("#FPG-execute").attr('disabled', true);
        fpg_guid = WebUploader.Base.guid();
        $.ajax({
            url: 'algorithm/FPG.do',
            type: 'POST',
            dataType: 'json',
            async: true,
            contentType: 'application/x-www-form-urlencoded',
            data: {
                guid: fpg_guid
            },
            beforeSend: function () {
                setFpgRunState(true);
            },
            success: function (path) {
                if (!path.status) {
                    fpg_polling();
                } else {
                    alert(path.msg);
                    setFpgRunState(false);
                }
            },
            error: function () {
                alert("网络繁忙，请稍后再试！");
                setFpgRunState(false);
            }
        });
    });

    //轮询检测算法是否完成
    function fpg_polling() {
        $.ajax({
            url: 'data/checkFPG.do',
            type: 'POST',
            async: true,
            dataType: 'json',
            data: {
                guid: fpg_guid
            },
            success: function (result) {
                //成功
                if (!result.status) //因为后台数据status为1 所以暂时把!result.status的！ 去掉了！
                {
                    setFpgRunState(false);
                    //alert(result.data);
                    fpg_getYS1(); //成功后就获取YS1的值

                    addItemToHistory(fpg_cookiePrefix, fpg_historyId, fpg_guid, new Date(), 'fpg_history_click');
                } else if (result.msg != 'no') {
                    alert("服务器报错：" + result.msg);
                    setFpgRunState(false);
                }
                //不成功 轮询
                else {
                    window.setTimeout(function () {
                        fpg_polling()
                    }, 30000);
                }
            },
            error: (function () {
                alert("轮询出错");
                setFpgRunState(false);
            })
        })
    }

    // $("#sel-ys1").click(function(event) {
    //    getYS1();
    // });
    // 
    //获得因素一下拉框中选择的内容dataYS1
    //option改变的时候才能post值，不变的时候没有值post！！！！
    var YS1;
    $("#sel-ys1").change(function (event) {
        YS1 = $("#sel-ys1 option:selected").text();
        getYS2();
    })


    function getYS2() {
        $.ajax({
            url: 'data/getYS2.do',
            type: 'POST',
            async: true,
            dataType: 'json',
            data: {
                YS1: YS1,
                guid: fpg_guid
            },
            //result 因素二数组
            success: function (result) {
                if (!result.status) {
                    $('#sel-ys2').html('<option selected="true" disabled="true" value="0">请选择</option>');
                    fpg_addOption(result, "#sel-ys2");
                } else {
                    alert(result.msg);
                }

                //若含有与因素一相同的内容则不能再选 
                $("#sel-ys2 option").each(function () {
                    var unClick = $(this).text();
                    if (YS1 == unClick) {
                        $(this).attr('disabled', 'true');
                    }
                })

            },
            error: function () {
                alert("因素2获取失败");
            }

        })
    }
    //请求因素二
    var YS2;
    $("#sel-ys2").change(function (event) {
        YS2 = $("#sel-ys2 option:selected").text();
        setTable();
    })

    function setTable() {
        $.ajax({
            url: 'data/getYsglTable.do',
            type: 'POST',
            async: true,
            dataType: 'json',
            data: {
                YS1: YS1,
                YS2: YS2,
                guid: fpg_guid
            },
            success: function (result) {
                if (!result.status) {
                    createTable(result);
                    createchart(result);
                } else {
                    alert(result.msg);
                }
            },
            error: function () {
                alert("表格失败!");
            }
        })
    }

    function createTable(result) {
        var i, j;
        var rTable = document.getElementById("relate-table");
        rTable.innerHTML = "";
        for (i in result.data) {
            var tr = rTable.insertRow(i);
            for (j in result.data[i]) {
                var td = tr.insertCell(j);
                if (i == 0 && j == 0) {
                    td.innerHTML = '<div class="cause-table-line">' +
                        '<table class="inner-table">' +
                        '<tr>' +
                        '<th></th>' +
                        '<th id="ys2_text">' + YS2 + '</th>' +
                        '</tr>' +
                        '<tr>' +
                        '<th id="ys1_text">' + YS1 + '</th>' +
                        '<th></th>' +
                        '</tr>' +
                        '</table>' +
                        '</div>';
                } else {
                    td.innerHTML = result.data[i][j];
                }
            }
            $("#tab-ul").css("display","block");
        }
        j++;
        var persent = 100 / j;
        var tableWidth = persent.toString();
        tableWidth += "%";
        $(".cause-table td").css({
            width: tableWidth,
            minwidth: '10%'
        });
    }

});

//请求因素一数组
function fpg_getYS1() {
    $.ajax({
        url: 'data/getYS1.do',
        type: 'POST',
        async: true,
        dataType: 'json',
        data: {
            guid: fpg_guid
        },
        success: function (result) {
            //result因素一的数组 成功后插入元素
            if (!result.status) {
                $('#sel-ys1').html('<option selected="true" disabled="true" value="0">请选择</option>');
                $('#sel-ys2').html('<option selected="true" disabled="true" value="0">请选择</option>');
                fpg_addOption(result, "#sel-ys1");
            } else {
                alert(result.msg);
            }
        },
        error: function () {
            alert("因素1获取失败");
        }
    })
}

function fpg_addOption(result, id) {
    $(id).html('');
    for (var index in result.data) {
        var sel = $(id);
        var opt = document.createElement('option');
        opt.innerHTML = result.data[index];
        sel.append(opt);
    }
    $(id).trigger('change');
}

function fpg_history_click(sender) {
    fpg_guid = $(sender).attr('value');
    fpg_getYS1();
}

function createchart(jsondata){
            var myChart=echarts.init(document.getElementById('main'));
            var chartdata=[];
/*          chartdata.push({name:'一'}); 
            chartdata.push({name:'二'}); 
            chartdata.push({name:'三'}); 
            chartdata.push({name:'四'}); */
            //注入列因素（ys1）
            for(let i=1;i<jsondata.data[0].length;i++){
                chartdata.push({itemStyle: {color: 'auto'},name:jsondata.data[0][i]})
            }
            //注入行因素（ys2）
            for(let i=1;i<jsondata.data.length;i++){
                chartdata.push({itemStyle: {color: 'skyblue'},name:jsondata.data[i][0]})
            }
            //注入连接link      
            var chartlink=[];
/*          chartlink.push({source:'一', target:'二',name:'关系'})
            chartlink.push({source:'二', target:'四',name:'关系'})

            chartlink.push({source:'三', target:'二',name:'关系'})*/
            for(let i=1;i<jsondata.data.length;i++){
                for(let j=1;j<jsondata.data[0].length;j++){
                    if(jsondata.data[i][j]!=null)
                    chartlink.push({source:jsondata.data[i][0],target:jsondata.data[0][j],name:jsondata.data[i][j]})
                }
            }
            //配置
            option = {
                title: {    
                    text:'一张图'
                },
                series: [{  
                        roam: true,
                        force: {
                            repulsion: 600,
                            edgeLength: 80
                    },  
                        edgeLabel: {
                            normal: {
                                show: true,
                                formatter: function (x) {
                                    return x.data.name;
                                }
                            }
                    },          
                        type: 'graph',
                        layout:'force', 

                        edgeSymbolSize: [4, 10],            
                        data:chartdata,
                        label:{
                            show:'true'
                        },
                        symbolSize:50,
                        links:chartlink,
                        
                }],
            }
            myChart.setOption(option);
}